from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from .serializer import *
from rest_framework.response import Response
from django.core.paginator import Paginator


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user_obj = UserModel.objects.filter(username=username).first()
        if user_obj:
            if password == user_obj.password:
                return Response({'msg': '登录成功', 'code': 200, 'user_id': user_obj.id})
            else:
                return Response({'msg': '用户名或密码错误', 'code': 400})
        else:
            return Response({'msg': '用户名或密码错误', 'code': 400})


class NewsView(APIView):
    def get(self, request):
        current_page = request.query_params.get('current_page')
        news_obj = NewsModel.objects.all()
        paginotor = Paginator(news_obj, 3)
        paged = paginotor.page(current_page)
        ser = NewsSer(paged, many=True)
        return Response({
            'data': ser.data,
            'page_list': [i for i in paginotor.page_range],
            'page_sum': paginotor.num_pages
        })


class NewsInfoView(APIView):
    def get(self, request):
        news_id = request.query_params.get('news_id')
        news_obj = NewsModel.objects.filter(pk=news_id).first()
        ser = NewsSer(news_obj)
        return Response(ser.data)


class NewsStarsView(APIView):
    def post(self,request):
        news_id=request.data.get('news_id')
        news_obj=NewsModel.objects.filter(pk=news_id).first()
        if news_obj:
            news_obj.stars += 1
            news_obj.save()
            return Response({'msg':'点赞成功','code':200})
        else:
            return Response({'msg': '点赞失败', 'code': 400})